#include <stdio.h>
#include <sys/types.h>         
#include <sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <linux/input.h>
 
//ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,struct sockaddr *src_addr, socklen_t *addrlen);
 
 
 
int main()
{
	//1.创建socket
	int skfd=socket(AF_INET ,SOCK_DGRAM, 0);
	if(skfd == -1)
	{
		perror("socket fail");
	}
	else
	{
		printf("skfd=%d\n",skfd);
	}
	
	//2.bind IP和端口号
	//定义结构体
	struct sockaddr_in  seraddr={0};
	
	seraddr.sin_family=AF_INET; //IPV4
	seraddr.sin_port= htons(12345);
	//端口号 http-80 8080  Telnet--23 范围:0~65535  个人编程的时候建议5位数的端口号
	//htons()  把本地转换为网络序  认识大端和小端存储
	seraddr.sin_addr.s_addr=htonl(INADDR_ANY);
	//htonl() 课后 认识一下  转换为网络序  INADDR_ANY--0.0.0.0--表示自动获取本机IP
	
	int b_ret=bind(skfd, (struct sockaddr*)&seraddr,sizeof(seraddr));
	if(b_ret !=0)
	{
		perror("bind fail");
	}
	else
	{
		printf("bind ok\n");
	}
	
	int r_ret=0; //返回值
	char buf[512]={0}; //存储读取内容
	struct sockaddr_in  cliaddr={0}; //来自客户端地址
	socklen_t addrlen=sizeof(cliaddr); //地址长度
	
    long long  msg[3];



	while(1)
	{
		FILE* fp=fopen("1.txt","w");
		if (fp == NULL) {
        printf("无法打开文件。\n");
    	exit(-1);
		}
        memset(msg, 0, sizeof(msg));
		//接收消息
		r_ret=recvfrom(skfd, msg,sizeof(msg),0,(struct sockaddr*)&cliaddr, &addrlen);
		while(r_ret>=0)
		{
			if(sizeof(msg) > 0)
			{
				printf("Received: %lld %f %f\n", msg[0],(float)msg[1],(float)msg[2]);
        		fprintf(fp, "%lld %f %f\n", msg[0],(float)msg[1],(float)msg[2]);
				fflush(fp);
			}else{
				printf("Received an empty message\n");
			}
			
			memset(msg, 0, sizeof(msg));
			r_ret=recvfrom(skfd, msg,sizeof(msg),0,(struct sockaddr*)&cliaddr, &addrlen);
		}
		fclose(fp);
		memset(&cliaddr,0,sizeof(cliaddr));
		
	}
	
	//关闭通信
	close(skfd);
	
}